using BasicData.API.Services;
using BasicData.ErrorCode;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BasicData.API.Controllers
{
    /// <summary>
    /// 缓存控制器11111111111111111111111111111111111111111111111111111111111111111111
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("AllowAll")]
    public class CacheController : ControllerBase
    {
        private readonly RedisCacheService _cacheService;
        private readonly ILogger<CacheController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cacheService">缓存服务</param>
        /// <param name="logger">日志</param>
        public CacheController(RedisCacheService cacheService, ILogger<CacheController> logger)
        {
            _cacheService = cacheService;
            _logger = logger;
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <param name="value">缓存值</param>
        /// <param name="expiryMinutes">过期时间（分钟）</param>
        /// <returns>操作结果</returns>
        [HttpPost("set")]
        public IActionResult Set(string key, string value, int? expiryMinutes = null)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return BadRequest(new APIResult<string>
                    {
                        Code = ResultCode.添加失败,
                        Message = "缓存键不能为空"
                    });
                }

                TimeSpan? expiry = expiryMinutes.HasValue ? TimeSpan.FromMinutes(expiryMinutes.Value) : null;
                bool result = _cacheService.Set(key, value, expiry);

                return Ok(new APIResult<bool>
                {
                    Code = result ? ResultCode.添加成功 : ResultCode.添加失败,
                    Message = result ? "缓存设置成功" : "缓存设置失败",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置缓存失败: {Key}", key);
                return StatusCode(500, new APIResult<string>
                {
                    Code = ResultCode.添加失败,
                    Message = $"设置缓存失败: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <returns>缓存值</returns>
        [HttpGet("get")]
        public IActionResult Get(string key)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return BadRequest(new APIResult<string>
                    {
                        Code = ResultCode.查询失败,
                        Message = "缓存键不能为空"
                    });
                }

                if (!_cacheService.Exists(key))
                {
                    return NotFound(new APIResult<string>
                    {
                        Code = ResultCode.查询失败,
                        Message = "缓存不存在"
                    });
                }

                string value = _cacheService.Get<string>(key);

                return Ok(new APIResult<string>
                {
                    Code = ResultCode.查询成功,
                    Message = "获取缓存成功",
                    Data = value
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取缓存失败: {Key}", key);
                return StatusCode(500, new APIResult<string>
                {
                    Code = ResultCode.查询失败,
                    Message = $"获取缓存失败: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <returns>操作结果</returns>
        [HttpDelete("delete")]
        public IActionResult Delete(string key)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return BadRequest(new APIResult<string>
                    {
                        Code = ResultCode.删除失败,
                        Message = "缓存键不能为空"
                    });
                }

                bool result = _cacheService.Remove(key);

                return Ok(new APIResult<bool>
                {
                    Code = result ? ResultCode.删除成功 : ResultCode.删除失败,
                    Message = result ? "删除缓存成功" : "删除缓存失败",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除缓存失败: {Key}", key);
                return StatusCode(500, new APIResult<string>
                {
                    Code = ResultCode.删除失败,
                    Message = $"删除缓存失败: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 按模式删除缓存
        /// </summary>
        /// <param name="pattern">模式</param>
        /// <returns>操作结果</returns>
        [HttpDelete("delete-by-pattern")]
        public IActionResult DeleteByPattern(string pattern)
        {
            try
            {
                if (string.IsNullOrEmpty(pattern))
                {
                    return BadRequest(new APIResult<string>
                    {
                        Code = ResultCode.删除失败,
                        Message = "模式不能为空"
                    });
                }

                int count = _cacheService.RemoveByPattern(pattern);

                return Ok(new APIResult<int>
                {
                    Code = ResultCode.删除成功,
                    Message = $"删除了 {count} 个缓存",
                    Data = count
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "按模式删除缓存失败: {Pattern}", pattern);
                return StatusCode(500, new APIResult<string>
                {
                    Code = ResultCode.删除失败,
                    Message = $"按模式删除缓存失败: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 检查缓存是否存在
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <returns>是否存在</returns>
        [HttpGet("exists")]
        public IActionResult Exists(string key)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return BadRequest(new APIResult<string>
                    {
                        Code = ResultCode.查询失败,
                        Message = "缓存键不能为空"
                    });
                }

                bool exists = _cacheService.Exists(key);

                return Ok(new APIResult<bool>
                {
                    Code = ResultCode.查询成功,
                    Message = exists ? "缓存存在" : "缓存不存在",
                    Data = exists
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查缓存是否存在失败: {Key}", key);
                return StatusCode(500, new APIResult<string>
                {
                    Code = ResultCode.查询失败,
                    Message = $"检查缓存是否存在失败: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 设置缓存过期时间
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <param name="expiryMinutes">过期时间（分钟）</param>
        /// <returns>操作结果</returns>
        [HttpPost("set-expiry")]
        public IActionResult SetExpiry(string key, int expiryMinutes)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return BadRequest(new APIResult<string>
                    {
                        Code = ResultCode.更新失败,
                        Message = "缓存键不能为空"
                    });
                }

                if (!_cacheService.Exists(key))
                {
                    return NotFound(new APIResult<string>
                    {
                        Code = ResultCode.更新失败,
                        Message = "缓存不存在"
                    });
                }

                TimeSpan expiry = TimeSpan.FromMinutes(expiryMinutes);
                bool result = _cacheService.SetExpiry(key, expiry);

                return Ok(new APIResult<bool>
                {
                    Code = result ? ResultCode.更新成功 : ResultCode.更新失败,
                    Message = result ? "设置缓存过期时间成功" : "设置缓存过期时间失败",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置缓存过期时间失败: {Key}", key);
                return StatusCode(500, new APIResult<string>
                {
                    Code = ResultCode.更新失败,
                    Message = $"设置缓存过期时间失败: {ex.Message}"
                });
            }
        }
    }
} 